import numpy as np
from PIL import Image
import ctypes
import sys


def load_image_bgra(filepath):
    """Load PNG and convert to BGRA_8888 format"""
    # Load image with PIL
    img = Image.open(filepath)

    # Convert to RGBA if not already
    if img.mode != "RGBA":
        img = img.convert("RGBA")

    # Convert to numpy array
    rgba_array = np.array(img, dtype=np.uint8)

    # Convert RGBA to BGRA by swapping R and B channels
    bgra_array = rgba_array.copy()
    bgra_array[:, :, [0, 2]] = bgra_array[:, :, [2, 0]]  # Swap R and B

    return bgra_array


def process_image(bgra_buffer):
    """Call C++ function with BGRA buffer"""
    # Load your C++ shared library
    lib = ctypes.CDLL("./image_processor.so")  # or .dll on Windows

    # Define function signature
    lib.process_image.argtypes = [
        ctypes.POINTER(ctypes.c_uint8),  # buffer pointer
        ctypes.c_int,  # width
        ctypes.c_int,  # height
        ctypes.c_int,  # stride (bytes per row)
    ]
    lib.process_image.restype = ctypes.c_int

    height, width, channels = bgra_buffer.shape
    stride = width * channels

    # Get pointer to buffer data
    buffer_ptr = bgra_buffer.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))

    # Call C++ function
    result = lib.process_image(buffer_ptr, width, height, stride)

    return result


# Usage
if __name__ == "__main__":
    bgra_buffer = load_image_bgra(sys.argv[1])
    result = process_image(bgra_buffer)
    print(f"Processing result: {result}")
